import request from '@/utils/request';
import type { OptionTypes, ResponseData } from '@/utils/types.d';
import { SUCCESS_CODE } from '@/utils/types.d';
import type { CreateParkingspotType, SpotTableItem, UpdateParkingspotType } from './types.d';

export async function queryParkingspots(params: any, sort: any) {
  const res: ResponseData<{
    total: number;
    data: SpotTableItem[];
  }> = await request('/api/parkingspot/v1.0.0/parkingspots', {
    params: {
      data: params,
      sort,
    },
  });
  if (res?.code === SUCCESS_CODE)
    return { success: true, total: res.data.total, data: res.data.data };
  return { success: false, total: 0, data: [] };
}

export async function queryParkinglotNames(parkingLotName?: string, ownerId?: string) {
  const res: ResponseData<OptionTypes[]> = await request('/api/parkinglot/v1.0.0/parkingLotNames', {
    params: { parkingLotName, ownerId },
  });
  if (res?.code === SUCCESS_CODE) {
    return res.data;
  }
  return [];
}

export async function createParkingspot(params: CreateParkingspotType) {
  const res: ResponseData<SpotTableItem> = await request('/api/parkingspot/v1.0.0/parkingspot', {
    method: 'POST',
    data: params,
  });
  if (res?.code === SUCCESS_CODE)
    return {
      data: res.data,
      success: true,
      message: '添加成功',
    };
  return {
    data: res?.data,
    success: false,
    message: res?.message || '添加失败',
  };
}

export async function updateParkingspot(id: string, newInfo: UpdateParkingspotType) {
  if (!id || !newInfo || Object.keys(newInfo).length === 0)
    return { success: false, message: '更新失败，请填入需要更新的信息' };
  const res: ResponseData<null> = await request(`/api/parkingspot/v1.0.0/parkingspot/${id}`, {
    method: 'PUT',
    data: newInfo,
  });
  if (res?.code === SUCCESS_CODE) return { success: true, data: res.data, message: '更新成功' };
  return { success: false, data: res?.data, message: res?.message || '更新失败' };
}

export async function removeParkingspot(id: string) {
  const res: ResponseData<null> = await request(`/api/parkingspot/v1.0.0/parkingspot/${id}`, {
    method: 'DELETE',
  });
  if (res?.code === SUCCESS_CODE) return { success: true, message: '删除成功' };
  return { success: false, message: res?.message || '删除失败' };
}

// 导出文件
export async function exportParkingspots(params: { ownerId?: string; parkingLotId?: string }) {
  return await request('/api/parkingspot/v1.0.0/export-spot', {
    params,
    responseType: 'blob',
  });
}

export async function deleteMulSpots(ids: string[]) {
  const res: ResponseData<null> = await request('/api/parkingspot/v1.0.0/multi-spot', {
    method: 'DELETE',
    data: {
      ids,
    },
  });
  if (res?.code === SUCCESS_CODE) return { success: true, message: '删除成功' };
  return { success: false, message: res?.message || '删除失败' };
}
